package cn.gd.service.systemAdministration.Role.Impl;

import cn.gd.mapper.systemAdministration.Role.RoleMapper;
import cn.gd.pojo.Roles;
import cn.gd.service.systemAdministration.Role.RoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public PageInfo<Roles> queryAllRoles(Integer pageNo, Integer pageSize) {
        PageHelper.startPage(pageNo,pageSize);
        return new PageInfo<>(roleMapper.queryAllRoles());
    }

    @Override
    public Boolean updateRole(Roles role) {
        boolean flag = false;
        int roleId;
        roleId = roleMapper.queryRoleIdByRoleOrder(role.getRoleOrder());
        int row1 = 0;

        if(roleId != role.getRoleID()){
            row1 = roleMapper.updateAllRoleOrderPlusOneByRoleOrder(role.getRoleOrder());
        }
        int row2 = roleMapper.updateRole(role);
        if(row1 > 0){
            if(row2>0){
                flag = true;
            }
        }
        return flag;
    }

    @Override
    public Boolean deleteRoleByRoleId(Integer roleId) {
        boolean flag = false;
        int count = roleMapper.queryWhetherTheRoleIsUsedByUsers(roleId);//查询有没有用户使用
        if(count == 0){
            int roleOrder = roleMapper.queryRoleOrderByRoleId(roleId);//查询排序序号
            int row1 = roleMapper.updateAllRoleOrderMinusOneByRoleOrder(roleOrder);//该角色后的排序减一
            int row = roleMapper.deleteRoleByRoleId(roleId);//删除角色
            if(row1 > 0) {
                if (row > 0) {
                    flag = true;
                }
            }
        }
        return flag;
    }

    @Override
    public Boolean addRole(Roles role) {
        int roleId = roleMapper.queryRoleIdByRoleOrder(role.getRoleOrder());
        boolean flag = false;
        int row1 = 0;
        if(roleId != 0){
            row1 = roleMapper.updateAllRoleOrderPlusOneByRoleOrder(role.getRoleOrder());
        }
        int row = roleMapper.addRole(role);
        if(row1 > 0){
            if(row > 0) {
                flag = true;
            }
        }
        return flag;
    }
}
